package com.wind.cloud.common.util;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求上下文
 *
 * @author wind.
 */
public class RequestContextUtils {

    public static HttpServletRequest getRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        if (ra != null) {
            return ((ServletRequestAttributes) ra).getRequest();
        }
        return null;
    }

    public static HttpServletResponse getResponse() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        if (ra != null) {
            return ((ServletRequestAttributes) ra).getResponse();
        }
        return null;
    }

    public static Object getSessionAttribute(String key) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return WebUtils.getSessionAttribute(request, key);
        }
        return null;
    }

    public static void removeSessionAttribute(String key) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            WebUtils.setSessionAttribute(request, key, null);
        }
    }

    public static void setSessionAttribute(String key, Object val) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            WebUtils.setSessionAttribute(request, key, val);
        }
    }

}
